const express = require('express');
const { md5 } = require('utility');
const router = express.Router();
const db = require('../db');

//获取用户信息
router.get('/userinfo',(req,res)=>{
    // console.log(req.user);
    db(`select * from user where id=${req.user.id}`,(err,result)=>{
        if(err) throw err;
        res.send({
            status:0,
            message:"获取用户信息成功",
            data:result[0]
        })
    })
})

//更新用户信息
router.post('/userinfo',(req,res)=>{
    
    // console.log(req.user);
    let {nickname,email} = req.body;
    
    db(`update user set nickname="${nickname}",email="${email}" where id=${req.user.id}`,(err,result)=>{
        if(err) throw err;
        res.send({
            status:0,
            message:'更新用户信息成功'
        })
    })
})

//更换头像
router.post('/avatar',(req,res)=>{
    // console.log(req.user.id);
    db(`update user set user_pic="${req.body.avatar}" where id=${req.user.id}`,(err,result)=>{
        if(err) throw err;
        res.send({
            status:0,
            message:'更换头像成功'
        })
    })
})

//更换密码
router.post('/updatepwd',(req,res)=>{
    let {oldPwd,newPwd} = req.body;
    oldPwd = md5(oldPwd);
    newPwd = md5(newPwd);
    db(`select * from user where id=${req.user.id} and password="${oldPwd}"`,(err,result)=>{

        if(result.length > 0){
            db(`update user set password="${newPwd}" where id=${req.user.id}`,(e,r)=>{
                if(e) throw e;
                res.send({
                    status:0,
                    message:'密码更新成功'
                })
            })
        }else{
            res.send({
                status:1,
                message:'原密码错误'
            })
        }
    })
})


module.exports = router;


